using System;
using System.IO;
using System.Drawing;
using System.Windows.Forms;
using System.ComponentModel;
using WeifenLuo.WinFormsUI.Docking;
using PluginCore.Localization;
using PluginCore.Utilities;
using PluginCore.Managers;
using PluginCore.Helpers;
using PluginCore;
using AirProperties.Resources;

namespace AirProperties
{
	public class PluginMain : IPlugin
	{
        private String pluginName = "AIRProperties";
        private String pluginGuid = "d4076fbc-5798-4355-8e54-3c2adcc7c7e6";
        private String pluginHelp = "http://livedocs.adobe.com/flex/3/html/File_formats_1.html#1043413";
        private String pluginDesc = "Adds an AIR application properties management form for AIR projects.";
        private String pluginAuth = "Sam Anthonisz";
        private String settingFilename;
        private Settings settingObject;

        private AirWizard wizard;
        private Image pluginImage;

        private ToolStripButton pluginToolbarItem;
        private ToolStripSeparator pluginToolbarSeparator;
        private ToolStripItem pluginMenuItem;
        private ToolStrip pluginToolStrip;


	    #region Required Properties

        /// <summary>
        /// Name of the plugin
        /// </summary> 
        public String Name
		{
			get { return this.pluginName; }
		}

        /// <summary>
        /// GUID of the plugin
        /// </summary>
        public String Guid
		{
			get { return this.pluginGuid; }
		}

        /// <summary>
        /// Author of the plugin
        /// </summary> 
        public String Author
		{
			get { return this.pluginAuth; }
		}

        /// <summary>
        /// Description of the plugin
        /// </summary> 
        public String Description
		{
			get { return this.pluginDesc; }
		}

        /// <summary>
        /// Web address for help
        /// </summary> 
        public String Help
		{
			get { return this.pluginHelp; }
		}

        /// <summary>
        /// Object that contains the settings
        /// </summary>
        [Browsable(false)]
        Object IPlugin.Settings
        {
            get { return this.settingObject; }
        }

        /// <summary>
        /// Internal access to settings
        /// </summary>
        [Browsable(false)]
        public Settings Settings
        {
            get { return this.settingObject; }
        }
		
		#endregion
		
		#region Required Methods
		
		/// <summary>
		/// Initializes the plugin
		/// </summary>
		public void Initialize()
		{
            this.InitBasics();
            this.LoadSettings();
            this.AddEventHandlers();
            this.InitLocalization();
        }
		
		/// <summary>
		/// Disposes the plugin
		/// </summary>
		public void Dispose()
		{
            this.SaveSettings();
		}
		
		/// <summary>
		/// Handles the incoming events
		/// </summary>
		public void HandleEvent(Object sender, NotifyEvent e, HandlingPriority prority)
		{
            switch (e.Type)
            {
                // Catches Project change event 
                case EventType.Command:
                    string cmd = (e as DataEvent).Action;
                    if (cmd == "ProjectManager.Project")
                    {
                        ConfigurePlugin();
                    }
                    break;

                default:
                    break;
            } 
		}
		
		#endregion

        #region Custom Methods
       
        /// <summary>
        /// Initializes important variables
        /// </summary>
        public void InitBasics()
        {

            String dataPath = Path.Combine(PathHelper.DataDir, "AIRProperties");
            if (!Directory.Exists(dataPath)) Directory.CreateDirectory(dataPath);
            this.settingFilename = Path.Combine(dataPath, "Settings.fdb");
            this.pluginImage = PluginBase.MainForm.FindImage("100");
        }

        /// <summary>
        /// Adds the required event handlers
        /// </summary> 
        public void AddEventHandlers()
        {
            // Set events you want to listen (combine as flags)
            EventManager.AddEventHandler(this, EventType.Command);
        }

        /// <summary>
        /// Initializes the localization of the plugin
        /// </summary>
        public void InitLocalization()
        {
            LocaleVersion locale = PluginBase.MainForm.Settings.LocaleVersion;
            switch (locale)
            {
                /*
                case LocaleVersion.fi_FI : 
                    // We have Finnish available... or not. :)
                    LocaleHelper.Initialize(LocaleVersion.fi_FI);
                    break;
                */
                default : 
                    // Plugins should default to English...
                   LocaleHelper.Initialize(LocaleVersion.en_US);
                    break;
            }
            this.pluginDesc = LocaleHelper.GetString("Info.Description");
        }


        /// <summary>
        /// Determines if the active project is an AIR project and adds/removes plugin toolbar/menu items accordingly
        /// </summary>
        public void ConfigurePlugin()
        {
            Boolean pluginActive = false;

            ToolStrip mainToolStrip = (ToolStrip)PluginBase.MainForm.ToolStrip;
            ToolStripMenuItem projectMenu = null;
            
            foreach (ToolStripItem item in PluginBase.MainForm.MenuStrip.Items)
            {
                //this is the only way I can see to find the project menu (not multi-locale compatible...)
                if (item.Text.Equals("&Project"))
                {
                    projectMenu = (ToolStripMenuItem)item;
                    break;
                }
            }

            //determine whether to activate the plugin
            if (PluginBase.CurrentProject != null && PluginBase.CurrentProject is ProjectManager.Projects.AS3.AS3Project)
            {
                //check if AS3 Project with AIR compliation option (requires a reference to ProjectManager but is most reliable method)
                ProjectManager.Projects.AS3.AS3Project project = (ProjectManager.Projects.AS3.AS3Project)PluginBase.CurrentProject;
                string[] compilerOptions = project.CompilerOptions.Additional;
                foreach (string compilerOption in compilerOptions)
                {
                    if (compilerOption.Contains("configname=air"))
                    {
                        pluginActive = true;
                    }
                }
            }

            if (pluginActive)
            {
                //add the toolbar and menu items (if not already there)
                if (mainToolStrip != null)
                {
                    if (pluginToolStrip == null)
                    {
                        pluginToolStrip = new ToolStrip();
                    }
                    if (pluginToolbarSeparator == null)
                    {
                        pluginToolbarSeparator = new ToolStripSeparator();
                    }
                    if (pluginToolbarItem == null)
                    {
                        pluginToolbarItem = new ToolStripButton(String.Empty, global::AirProperties.Properties.Resources.blockdevice_small, new EventHandler(this.OpenWizard), null);
                        pluginToolbarItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
                        pluginToolbarItem.ToolTipText = LocaleHelper.GetString("Tooltip.ToolStripItem");
                       
                    }
                    if (!mainToolStrip.Items.Contains(pluginToolbarItem))
                    {
                        mainToolStrip.Items.Add(pluginToolbarSeparator);
                        mainToolStrip.Items.Add(pluginToolbarItem);
                    }
                }
                if (projectMenu != null)
                {
                    if (pluginMenuItem == null)
                    {
                        pluginMenuItem = new ToolStripMenuItem(LocaleHelper.GetString("Label.ProjectMenuItem"), global::AirProperties.Properties.Resources.blockdevice_small, new EventHandler(this.OpenWizard), null);
                    }
                    if (!projectMenu.DropDownItems.Contains(pluginToolbarItem))
                    {
                        projectMenu.DropDownItems.Add(pluginMenuItem);
                    }
                }
            }
            else
            {
                //remove the toolbar and menu items (if active)
                if (mainToolStrip != null && pluginToolbarSeparator != null)
                {
                    if (mainToolStrip.Items.Contains(pluginToolbarSeparator))
                        mainToolStrip.Items.Remove(pluginToolbarSeparator);
                }
                if (mainToolStrip != null && pluginToolbarItem != null)
                {
                    if (mainToolStrip.Items.Contains(pluginToolbarItem))
                        mainToolStrip.Items.Remove(pluginToolbarItem);
                }
                if (projectMenu != null && pluginMenuItem != null)
                {
                    if (projectMenu.DropDownItems.Contains(pluginMenuItem))
                        projectMenu.DropDownItems.Remove(pluginMenuItem);
                }
            }
        }                

        /// <summary>
        /// Loads the plugin settings
        /// </summary>
        public void LoadSettings()
        {
            this.settingObject = new Settings();
            if (!File.Exists(this.settingFilename)) this.SaveSettings();
            else
            {
                Object obj = ObjectSerializer.Deserialize(this.settingFilename, this.settingObject);
                this.settingObject = (Settings)obj;
            }
        }

        /// <summary>
        /// Saves the plugin settings
        /// </summary>
        public void SaveSettings()
        {
            ObjectSerializer.Serialize(this.settingFilename, this.settingObject);
        }

        /// <summary>
        /// Opens the plugin panel if closed
        /// </summary>
        public void OpenWizard(Object sender, System.EventArgs e)
        {
           
            wizard = new AirWizard(this);
            //don't show the wizard if the properties weren't loaded
            if (wizard.IsPropertiesLoaded)
                this.wizard.ShowDialog(PluginBase.MainForm);
        }

		#endregion

	}
	
}
